package com.medical.app.repository;

import com.medical.app.entity.HealthRecord;
import org.springframework.data.jpa.repository.JpaRepository;
import org.springframework.data.jpa.repository.Query;
import org.springframework.data.repository.query.Param;
import org.springframework.stereotype.Repository;

import java.time.LocalDate;
import java.util.List;
import java.util.Optional;

@Repository
public interface HealthRecordRepository extends JpaRepository<HealthRecord, Long> {

    // 根据用户ID查找健康记录，按日期倒序排列
    List<HealthRecord> findByUserIdOrderByRecordDateDesc(Long userId);

    // 根据用户ID和日期查找健康记录
    Optional<HealthRecord> findByUserIdAndRecordDate(Long userId, LocalDate recordDate);

    // 根据用户ID和日期范围查找健康记录
    List<HealthRecord> findByUserIdAndRecordDateBetween(Long userId, LocalDate startDate, LocalDate endDate);

    // 查找用户最新的健康记录
    @Query("SELECT hr FROM HealthRecord hr WHERE hr.user.id = :userId ORDER BY hr.recordDate DESC LIMIT 1")
    Optional<HealthRecord> findLatestByUserId(@Param("userId") Long userId);

    // 统计用户的健康记录数量
    long countByUserId(Long userId);

    // 获取用户最近7天的健康记录
    @Query("SELECT hr FROM HealthRecord hr WHERE hr.user.id = :userId AND hr.recordDate >= :startDate ORDER BY hr.recordDate ASC")
    List<HealthRecord> findRecentRecords(@Param("userId") Long userId, @Param("startDate") LocalDate startDate);
}